<script>
import { defineComponent, inject, reactive, ref, toRaw } from 'vue'
import {
  tagList,
  tagDel,
  tagAddTagGroup,
  tagModifyTagGroup,
} from '@Config/server/api'
import DataTable from '@Components/dataTable'
import { createPagination, Messages } from '@Config/config'
import { message, Modal } from 'ant-design-vue'
import MakeForm, { MakeFormState } from '@Components/makeForm'
import ColorBlock from '@Components/colorBlock'
import { useUrl, transform_pre_fn } from '@Hooks/url'
import { useRoute } from 'vue-router'
import { instanceFn } from '@Page/mark/fn'
import { useWin } from '@Hooks/win'
import { DownOutlined } from '@ant-design/icons-vue'
import { findIndex } from 'lodash'
import MarkGroupForm from '@Page/myMarkGroup/components/form'

export default defineComponent({
  components: {
    DataTable,
    MakeForm,
    ColorBlock,
  },
  setup(props, context) {
    //注册右上角的菜单
    let rightMenu = inject('rightIconMenu')
    rightMenu.data = null

    let { cateFormWin, markFormWin } = instanceFn()
    let form_config = [
      // {
      //   key: 'showType',
      //   initValue: 0,
      //   uiType: 'select',
      //   source: _SHOW_TYPE_LIST_FN(),
      //   col: { span: 6 },
      //   formItem: { label: '可见用户类型' },
      //   attr: { placeholder: '可见用户类型' },
      // },
      // {
      //   key: 'type',
      //   initValue: 0,
      //   uiType: 'select',
      //   source: TYPE_LIST(),
      //   col: { span: 6 },
      //   formItem: { label: '公告类型' },
      //   attr: { placeholder: '公告类型' },
      // },
      // {
      //   key: 'button',
      //   initValue: null,
      //   uiType: 'custom',
      //   col: { span: 5 },
      //   ui: (
      //     <a-space>
      //       <a-button
      //         type="primary"
      //         onClick={searchHandler}
      //         v-slots={{
      //           icon: () => {
      //             return <SearchOutlined />
      //           },
      //         }}
      //         loading={loading.search_loading}
      //       >
      //         搜索
      //       </a-button>
      //       <a-button
      //         type="primary"
      //         danger
      //         onClick={resetHandler}
      //         v-slots={{
      //           icon: () => {
      //             return <ClearOutlined />
      //           },
      //         }}
      //         loading={loading.search_loading}
      //       >
      //         重置
      //       </a-button>
      //     </a-space>
      //   ),
      // },
    ]
    let form_state = reactive({ data: MakeFormState(form_config) })

    //表格数据配置
    let tableData = reactive({
      data: {
        source: [],
        columns: [
          {
            key: 'name',
            dataIndex: 'name',
            title: '好友分组',
            width: '10%',
          },
          {
            title: '好友名称',
            key: 'id',
            dataIndex: 'id',
            transform: (text, record, index) => {
              return (
                <a-space style={{ flexWrap: 'wrap' }}>
                  {record.child.map((x) => {
                    return (
                      <a-dropdown
                        vSlots={{
                          overlay: () => {
                            return (
                              <a-menu>
                                <a-menu-item>
                                  <a-button
                                    type="link"
                                    onClick={() => {
                                      markFormWin({
                                        params: {
                                          record: x,
                                        },
                                        attr2: {
                                          title: '编辑',
                                        },
                                      })
                                    }}
                                  >
                                    编辑
                                  </a-button>
                                </a-menu-item>
                                <a-menu-item>
                                  <a-popconfirm
                                    title="确定要删除该好友吗？"
                                    onConfirm={async () => {
                                      let _r = await tagDel({ id: x.id })
                                      if (_r.code == 0) {
                                        Messages.add(
                                          message.success(`操作成功`)
                                        )

                                        let _r2 = findIndex(
                                          tableData.data.source[index].child,
                                          { id: x.id }
                                        )
                                        if (_r2 >= 0) {
                                          tableData.data.source[
                                            index
                                          ].child.splice(_r2, 1)
                                        }
                                      } else {
                                        Messages.add(
                                          message.error(`操作失败[${_r.msg}]`)
                                        )
                                      }
                                    }}
                                  >
                                    <a-button type="link" danger>
                                      删除
                                    </a-button>
                                  </a-popconfirm>
                                </a-menu-item>
                              </a-menu>
                            )
                          },
                        }}
                      >
                        <a-button>
                          {x.name}
                          <DownOutlined />
                        </a-button>
                      </a-dropdown>
                    )
                  })}
                </a-space>
              )
            },
            width: '80%',
          },

          {
            key: 'operation',
            dataIndex: 'operation',
            width: '10%',
            title: '操作',
            transform: (text, record, index) => {
              return (
                <a-space direction="vertical">
                  <a-button
                    type="primary"
                    size="small"
                    danger
                    onClick={() => {
                      cateFormWin({
                        params: {
                          record: record,
                        },
                        attr2: {
                          title: '编辑分组',
                        },
                      })
                    }}
                  >
                    编辑分组
                  </a-button>
                  <a-popconfirm
                    title="删除分组后，分组内的好友将会一并删除，是否确定？"
                    onConfirm={async () => {
                      let _r = await tagDel({ id: record.id })
                      if (_r.code == 0) {
                        Messages.add(message.success(`操作成功`))
                        tableData.data.source.splice(index, 1)
                      } else {
                        Messages.add(message.error(`操作失败[${_r.msg}]`))
                      }
                    }}
                  >
                    <a-button type="primary" size="small">
                      删除分组
                    </a-button>
                  </a-popconfirm>

        
                </a-space>
              )
            },
          },
        ],
      },
    })

    //表格loading状态
    let loading = reactive({ search_loading: false, delete_loading: false })

    let resetHandler = () => {
      form_ref.value.resetState()
      pagination.data.current = 1
      searchData()
    }
    //查询按钮监听
    let searchHandler = () => {
      pagination.data.current = 1
      searchData()
    }
    let route = useRoute()

    let { fromStateToQuery } = useUrl({
      fn: async () => {
        loading.search_loading = true
        let _params = {
          // ...form_state.data,
          index: pagination.data.current,
          size: pagination.data.pageSize,
        }
        let _result = await tagList(_params)
        if (_result.code != 0) {
          Messages.add(message.error('查询失败' + _result.msg))
          return
        }
        pagination.data.pageSize = _result.data?.size
        pagination.data.current = _result.data?.index
        pagination.data.total = _result.data?.total
        tableData.data.source = _result.data?.records
        loading.search_loading = false
      },
      formState: [
        // {
        //   key: 'showType',
        //   fn: (x) => {
        //     if (x) {
        //       return Number(x)
        //     } else {
        //       return 0
        //     }
        //   },
        // },
        // {
        //   key: 'type',
        //   fn: (x) => {
        //     if (x) {
        //       return Number(x)
        //     } else {
        //       return 0
        //     }
        //   },
        // },
      ],
    })
    //查询数据
    let searchData = async () => {
      fromStateToQuery({ path: route.path })
    }

    //表格分页
    let pagination = reactive({
      data: createPagination(searchData, true, false),
    })

    //分页点击
    // pagination.data.onChange = (pageNumber, pageSize) => {
    //   pagination.data.current = pageNumber
    //   pagination.data.pageSize = pageSize
    //   searchData()
    // }
    //ref dom
    let form_ref = ref(null)
    //新增公告回调函数

    //默认查询
    //searchData()

    let createCateHandler = () => {
      cateFormWin({
        attr2: {
          title: '新建分组',
        },
      })
    }

    let createMarkHandler = () => {
      markFormWin({
        attr2: {
          title: '新建标签',
        },
      })
    }

    let createMarkHandlerByCate = (_pid) => {
      markFormWin({
        attr2: {
          title: '新建标签',
        },
        params: {
          record: { pid: _pid },
        },
      })
    }
    let [markGroupWin] = useWin({
      component: (
        <MarkGroupForm
          onResult={async ({ info, iCallBack }) => {
            if (info.id == 0) {
              //新增
              let _r = await tagAddTagGroup(info)
              if (_r.code == 0) {
                Messages.add(message.success(`操作成功`))
                tableData.data.source.push(_r.data)
              } else {
                Messages.add(message.error(`操作失败[${_r.msg}]`))
              }
              iCallBack(_r)
            } else {
              //修改编辑
              let _r = await tagModifyTagGroup(info)
              if (_r.code == 0) {
                Messages.add(message.success(`操作成功`))
                let _index = findIndex(tableData.data.source, { id: info.id })
                tableData.data.source.splice(_index, 1, _r.data)
              } else {
                Messages.add(message.error(`操作失败[${_r.msg}]`))
              }
              iCallBack(_r)
            }
          }}
        />
      ),
    })
    let createMarkGroupHandler = () => {
      markGroupWin({
        attr2: {
          title: '添加好友',
        },
      })
    }
    return {
      tableData,
      loading,
      pagination,
      form_config,
      form_state,
      form_ref,
      createCateHandler,
      createMarkHandler,
      createMarkHandlerByCate,
      createMarkGroupHandler,
    }
  },
  render() {
    return (
      <>
        {this.loading.search_loading ? (
          <a-spin tip="数据加载中" />
        ) : (
          <a-row gutter={[20, 20]}>
            <a-col span={24}>
              {
                //   <MakeForm
                //   ref="form_ref"
                //   formConfig={this.form_config}
                //   value={this.form_state.data}
                // />
              }
            </a-col>

            <a-col span={24}>
              <DataTable
                data={this.tableData}
                loading={this.loading}
                uiAttr={{
                  scroll: { x: null },
                  tableLayout: 'fixed',
                  bordered: true,
                }}
              >
                <a-space>
                  <a-button type="primary" onClick={this.createCateHandler}>
                    新建分组
                  </a-button>
               
                  <a-button
                    type="primary"
                    onClick={this.createMarkGroupHandler}
                  >
                    添加好友
                  </a-button>
                </a-space>
              </DataTable>
              <a-affix {...this.pagination_affix_attr()}>
                <div class="affix">
                  <a-pagination {...this.pagination.data} />
                </div>
              </a-affix>
            </a-col>
          </a-row>
        )}
      </>
    )
  },
})
</script>
